import { formatTime } from '../../../utils/util';
import { OrderStatus, LogisticsIconMap } from '../config';
import Toast from 'tdesign-miniprogram/toast';
import { getAddressPromise } from '../../usercenter/address/list/util';
import { fetchAddressList, createOrder, payOrder, fetchHousekeeperDetail, fetchDemandDetail, createDemandOrder } from '../../../utils/request';

 
Page({
  data: {
    pageLoading: true,
    order: {}, // 后台返回的原始数据
    _order: {}, // 内部使用和提供给 order-card 的数据
    storeDetail: {},
    countDownTime: null,
    addressEditable: false,
    backRefresh: false, // 用于接收其他页面back时的状态
    formatCreateTime: '', //格式化订单创建时间
    logisticsNodes: [],
    /** 订单评论状态 */
    orderHasCommented: true,
    buyNum: 0,
    commodityId: 0,
    commodity: {},
    addressList: [],
    addressMsg: {},
    payDialogContent: '',
    showPayDialog: false,
    orderId: 0,
    type: null,
    accommodation: 0,
    remark: '',
    chargeMode: 0,
    pay: null,
    beginTimeVisible: false,
    beginTime: '',
    endTimeVisible: false,
    endTime: '',
    currentTime: Date.parse(new Date()),
    serviceCount: null,
    pay: null,
    remark: '',
    buttonDisabled: false,
    demandToOrder: false,
    demand: {}
  },
  serviceCountHandle(e) {
    this.setData({
      serviceCount: e.detail.value
    })
  },

  payHandle(e) {
    this.setData({
      pay: e.detail.value
    })
  },
  remarkHandle(e) {
    this.setData({
      remark: e.detail.value
    })
  },

  onChargeModeChange(e) {
    this.setData({
      chargeMode: e.detail.value
    })
  },

  showEndPicker() {
    this.setData({
      endTimeVisible: true
    })
  },

  onEndTimeConfirm(e) {
    this.setData({
      endTime: e.detail.value
    })
  },

  hideEndPicker() {
    this.setData({
      endTimeVisible: false
    })
  },

  showDatePicker() {
    this.setData({
      beginTimeVisible: true
    })
  },

  onBeginTimeConfirm(e) {
    this.setData({
      beginTime: e.detail.value
    })
  },

  hidePicker() {
    this.setData({
      beginTimeVisible: false
    })
  },


  onAccommodationChange(e) {
    this.setData({ 
      accommodation: e.detail.value
    });
  },

  onTypeChange(e) {
    this.setData({ 
      type: e.detail.value
    });
  },

  async confirmPay() {
    const orderId = this.data.orderId;
    await payOrder(orderId);
    Toast({
      context: this,
      selector: '#t-toast',
      message: '支付成功',
    });
    wx.reLaunch({
      url: '/pages/order/order-detail/index?orderId=' + orderId,
    })
  },

  cancelPay() {
    const orderId = this.data.orderId;
    wx.reLaunch({
      url: '/pages/order/order-detail/index?orderId=' + orderId,
    })
  },

  onAddressSelect() {
    wx.navigateTo({
      url: `./components/address-list/index`,
    });
  },

  async housekeeperOrder() {
    const address = this.data.addressMsg;
      const serviceCount = this.data.serviceCount;
      const housekeeperId = this.data.housekeeperId;
      const type = this.data.type;
      const accommodation = this.data.accommodation;
      const chargeMode = this.data.chargeMode;
      const pay = this.data.pay;
      const beginTime = this.data.beginTime;
      const endTime = this.data.endTime;
      const remark = this.data.remark;
      if (!address || !address.id) {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '请选择服务地址',
        });
        return ;
      }
      if (!type) {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '请选择服务类型',
        });
        return ;
      }
      if (!accommodation && accommodation != 0) {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '请选择是否提供住宿',
        });
        return ;
      }
      if (!chargeMode && chargeMode != 0) {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '请选择结算方式',
        });
        return ;
      }
      if (!pay || pay <= 0) {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '每期薪资错误',
        });
        return ;
      }
      if (!serviceCount || serviceCount <= 0) {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '服务期数错误',
        });
        return ;
      }
      if (!endTime || !beginTime) {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '请选择预计服务时间',
        });
        return ;
      }
      const res = await createOrder({
        housekeeperId,
        beginTime,
        endTime,
        serviceCount,
        serviceTypeId: type,
        addressId: address.id,
        chargeMode,
        pay,
        accommodation,
        remark
      })
      return res;
  },


  async demandOrder() {
      const housekeeperId = this.data.housekeeperId;
      const demandId = this.data.demandId;
      const pay = this.data.pay;
      const beginTime = this.data.beginTime;
      const endTime = this.data.endTime;
      const remark = this.data.remark;
      const serviceCount = this.data.serviceCount;
      if (!pay || pay <= 0) {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '每期薪资错误',
        });
        return ;
      }
      if (!serviceCount || serviceCount <= 0) {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '服务期数错误',
        });
        return ;
      }
      if (!endTime || !beginTime) {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '请选择预计服务时间',
        });
        return ;
      }
      const res = await createDemandOrder({
        housekeeperId,
        beginTime,
        endTime,
        serviceCount,
        remark,
        demandId,
        pay
      })
      return res;
  },

  async handleCreateOrder() {
    this.setData({
      buttonDisabled: true
    })
    console.log("1111");
    try {
      let res;
      if (this.data.demandToOrder) {
        console.log("2222");
        res = await this.demandOrder();
      } else {
        console.log("3333");
        res = await this.housekeeperOrder();
      }
      console.log("1111", res);
      if (res && res.code == 200) {
        
        Toast({
          context: this,
          selector: '#t-toast',
          message: '签约成功',
          theme: 'success'
        });
        setTimeout(() => {
          wx.reLaunch({
            url: `/pages/order/order-list/index`,
          });
        }, 1000)
      } else {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '签约失败，请重试',
          theme: 'error'
        });
      }
    } finally {
      this.setData({
        buttonDisabled: false
      })
    }
  },

  handleSelected() {
    
  },

  async getAddressList() {
    const res = await fetchAddressList();
    this.setData({ 
      addressList: res.data
    });
  },

  onLoad(query) {
    console.log("query", query);
    this.setData({
      housekeeperId: query.housekeeperId,
      demandToOrder:  wx.getStorageSync('demand-to-order') == 1,
      demandId: wx.getStorageSync('demandId')
    })
    this.init();
    this.getAddressList();
    this.navbar = this.selectComponent('#navbar');
    this.pullDownRefresh = this.selectComponent('#wr-pull-down-refresh');
  },

  onShow() {
    // 当从其他页面返回，并且 backRefresh 被置为 true 时，刷新数据
    if (!this.data.backRefresh) return;
    this.onRefresh();
    this.setData({ backRefresh: false });
  },

  onPageScroll(e) {
    this.pullDownRefresh && this.pullDownRefresh.onPageScroll(e);
  },

  onImgError(e) {
    if (e.detail) {
      console.error('img 加载失败');
    }
  },

  // 页面初始化，会展示pageLoading
  async init() {
    this.setData({ pageLoading: true });
    await this.getHousekeeper();
    if (this.data.demandToOrder && this.data.demandId) {
      await this.getDemand();
    }

    this.setData({ pageLoading: false });
    // this.getDetail(orderId)
    //   .then(() => {
    //     this.setData({ pageLoading: false });
    //   })
    //   .catch((e) => {
    //     console.error(e);
    //   });
  },

  // 页面刷新，展示下拉刷新
  onRefresh() {
    this.init();
    // 如果上一页为订单列表，通知其刷新数据
    const pages = getCurrentPages();
    const lastPage = pages[pages.length - 2];
    if (lastPage) {
      lastPage.data.backRefresh = true;
    }
  },

  // 页面刷新，展示下拉刷新
  onPullDownRefresh_(e) {
    const { callback } = e.detail;
    return this.getHousekeeper().then(() => callback && callback());
  },

  getHousekeeper() {
    return fetchHousekeeperDetail(this.data.housekeeperId).then((res) => {
      const commodity = res.data;
      this.setData({
        commodity: commodity,
        type: commodity.typeList[0].id
      })
    });
  },

  getDemand() {
    return fetchDemandDetail(this.data.demandId).then((res) => {
      const demand = res.data;
      this.setData({
        demand: res.data,
        addressMsg: {
          name: demand.name,
          phone: demand.phone,
          province: demand.province,
          city: demand.city,
          town: demand.town,
          detail: demand.detail
        },
        type: demand.serviceTypeId,
        accommodation: demand.accommodation,
        chargeMode: demand.chargeMode,
        pay: demand.maxSalary
      })
    });
  },

  // 展开物流节点
  flattenNodes(nodes) {
    return (nodes || []).reduce((res, node) => {
      return (node.nodes || []).reduce((res1, subNode, index) => {
        res1.push({
          title: index === 0 ? node.title : '', // 子节点中仅第一个显示title
          desc: subNode.status,
          date: formatTime(+subNode.timestamp, 'YYYY-MM-DD HH:mm:ss'),
          icon: index === 0 ? LogisticsIconMap[node.code] || '' : '', // 子节点中仅第一个显示icon
        });
        return res1;
      }, res);
    }, []);
  },

  datermineInvoiceStatus(order) {
    // 1-已开票
    // 2-未开票（可补开）
    // 3-未开票
    // 4-门店不支持开票
    return order.invoiceStatus;
  },

  // 拼接省市区
  composeAddress(order) {
    return [
      //order.logisticsVO.receiverProvince,
      order.logisticsVO.receiverCity,
      order.logisticsVO.receiverCountry,
      order.logisticsVO.receiverArea,
      order.logisticsVO.receiverAddress,
    ]
      .filter((s) => !!s)
      .join(' ');
  },

  // 仅对待支付状态计算付款倒计时
  // 返回时间若是大于2020.01.01，说明返回的是关闭时间，否则说明返回的直接就是剩余时间
  computeCountDownTime(order) {
    if (order.orderStatus !== OrderStatus.PENDING_PAYMENT) return null;
    return order.autoCancelTime > 1577808000000
      ? order.autoCancelTime - Date.now()
      : order.autoCancelTime;
  },

  onCountDownFinish() {
    //this.setData({ countDownTime: -1 });
    const { countDownTime, order } = this.data;
    if (
      countDownTime > 0 ||
      (order && order.groupInfoVo && order.groupInfoVo.residueTime > 0)
    ) {
      this.onRefresh();
    }
  },

  onGoodsCardTap(e) {
    console.log("onGoodsCardTap", e);
    const { index } = e.currentTarget.dataset;
    wx.navigateTo({ url: `/pages/goods/details/index?spuId=${index}` });
  },

  onEditAddressTap() {
    getAddressPromise()
      .then((address) => {
        this.setData({
          'order.logisticsVO.receiverName': address.name,
          'order.logisticsVO.receiverPhone': address.phone,
          '_order.receiverAddress': address.address,
        });
      })
      .catch(() => {});

    wx.navigateTo({
      url: `/pages/usercenter/address/list/index?selectMode=1`,
    });
  },

  onOrderNumCopy() {
    wx.setClipboardData({
      data: this.data.order.orderNo,
    });
  },

  onDeliveryNumCopy() {
    wx.setClipboardData({
      data: this.data.order.logisticsVO.logisticsNo,
    });
  },

  onToInvoice() {
    wx.navigateTo({
      url: `/pages/order/invoice/index?orderNo=${this.data._order.orderNo}`,
    });
  },

  onSuppleMentInvoice() {
    wx.navigateTo({
      url: `/pages/order/receipt/index?orderNo=${this.data._order.orderNo}`,
    });
  },

  onDeliveryClick() {
    const logisticsData = {
      nodes: this.data.logisticsNodes,
      company: this.data.order.logisticsVO.logisticsCompanyName,
      logisticsNo: this.data.order.logisticsVO.logisticsNo,
      phoneNumber: this.data.order.logisticsVO.logisticsCompanyTel,
    };
    wx.navigateTo({
      url: `/pages/order/delivery-detail/index?data=${encodeURIComponent(
        JSON.stringify(logisticsData),
      )}`,
    });
  },

  /** 跳转订单评价 */
  navToCommentCreate() {
    wx.navigateTo({
      url: `/pages/order/createComment/index?orderNo=${this.orderNo}`,
    });
  },

  /** 跳转拼团详情/分享页*/
  toGrouponDetail() {
    wx.showToast({ title: '点击了拼团' });
  },

  clickService() {
    Toast({
      context: this,
      selector: '#t-toast',
      message: '您点击了联系客服',
    });
  },

  onOrderInvoiceView() {
    wx.navigateTo({
      url: `/pages/order/invoice/index?orderNo=${this.orderNo}`,
    });
  },
});
